package org.naughtybabystudio.android.crazydriver;

import java.io.IOException;

import org.naughtybabystudio.android.crazydriver.bluetoothSppManager.BluetoothSppManager;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class WelcomeActivity extends Activity {
	
	private BluetoothSppManager mCommMan=null;
	private Button mBtnConnect=null;
	private TextView mTvGear=null;
	private TextView mTvDir=null;
	
	private ToggleButton mBtnSwitch=null;
	private SendOrientationThread mThreadWorking=new SendOrientationThread(this);
	
	static public Handler mHandler=null;

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if(mThreadWorking.isWorking()) {
			mThreadWorking.safeStop();
		}
		mCommMan.restorePreviousBtState();
		super.onDestroy();
	}
    /** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.main);
        
        mHandler=new Handler();
		mTvGear=(TextView)this.findViewById(R.id.tvGears);
		mTvDir=(TextView)this.findViewById(R.id.tvDirection);
       
        mBtnConnect=(Button)this.findViewById(R.id.btnConnectToyVehicle);
		mBtnConnect.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				mCommMan.connect();
			}		
		});
		
		mBtnSwitch=(ToggleButton)this.findViewById(R.id.btnControllerSwitch);
		mBtnSwitch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mBtnSwitch.isChecked()==true) {
					if( !mThreadWorking.isWorking()) {
						mThreadWorking=new SendOrientationThread(WelcomeActivity.this);
						mThreadWorking.start();
					}
					else {
						mThreadWorking.safeStop();
					}
				}
				else if(mBtnSwitch.isChecked()==false) {
					if( mThreadWorking.isWorking()) {
						mThreadWorking.safeStop();
					}
				}
			}
		});
		
        mCommMan=new BluetoothSppManager(this);

    }
	class SendOrientationThread extends Thread implements SensorEventListener {
		private Context mContext=null;
		private SensorManager mSensorManager = null;
		private Sensor mSensorOrientation=null;
		private Sensor mSensorAccelerometer=null;
		public boolean mIsWorking=false;
		
		public SendOrientationThread(Context context) {
			super();
			mContext=context;
		}
		public void run() {
			//validation
			if(mCommMan.canSppWork()) {
				//start working
				mIsWorking=true;
				mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
				mSensorOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
				mSensorAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
				mSensorManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_NORMAL);
				mSensorManager.registerListener(this, mSensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
				//working
				while(mIsWorking) {
					;
				}
				//end work
				mSensorManager.unregisterListener(this);
			}
			else {
				mHandler.post(new Runnable(){
					@Override
					public void run() {
						Toast.makeText(mContext, "No connection available", 1000).show();
					}
				});
			}
			mHandler.post(new Runnable(){
				@Override
				public void run() {
					mBtnSwitch.setChecked(false);
				}
			});
		}
		@Override
		public void onAccuracyChanged(Sensor arg0, int arg1) {		
		}
		@Override
		public void onSensorChanged(SensorEvent event) {
			if( event.sensor.getType()!=Sensor.TYPE_ORIENTATION) {
				return;
			}
			
			int gear=(int)(event.values[2]);
			int dir=(int)(event.values[1]);
			
           	final String strGear=String.format("%4d",gear);
           	final String strDir=String.format("%4d",dir);
           	mHandler.post(new Runnable() {
				@Override
				public void run() {
		           	mTvGear.setText(strGear);
		           	mTvDir.setText(strDir);
				}
           	});
           	
           	try {
           		if(gear>127) gear=127;
           		else if(gear<-127) gear=-127;
           		if(dir>127) dir=127;
           		else if(dir<-127) dir=-127;
           		
           		byte[] s=new byte[3];
           		s[0]=(byte)(gear&0xff);
           		s[1]=(byte)(dir&0xff);
           		s[2]=(byte)-128;//sync code
           			
           		mCommMan.writeStream(s);
           		//String strAll=strGear+" "+strDir+"\r\n";
           		//mCommMan.writeStream(strAll.getBytes());
			} catch (IOException e) {
				safeStop();
				Toast.makeText(mContext, "Connection lost", 1000).show();
			}
			
		}
		public void safeStop() {
			mIsWorking=false;
		}
		public boolean isWorking() {
			return mIsWorking;
		}
	}
}